package cevent.source.cloudcenter.server.util;/**
 * Created by Cevent on 2021/5/8.
 */

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.InputStream;

/**
 * @author cevent
 * @description VOD视频加密点播工具类
 * @date 2021/5/8 10:01
 */
public class VODUtil {
    private static final Logger LOG= LoggerFactory.getLogger(VODUtil.class);
    /**
     * 1.初始化VOD客户端，获取文件读取权限
     */
    public static DefaultAcsClient initVODClient(String ACCESS_KEY,String ACCESS_KEY_SECRET){
        //1.点播服务接入region区域，国内cn-shanghai 国外 cn-beijing
        String regionID="cn-shanghai";
        //2.获取文件读取权限
        DefaultProfile defaultProfile=DefaultProfile.getProfile(regionID,ACCESS_KEY,ACCESS_KEY_SECRET);
        //3.将读取文件权限传递给acsClient
        DefaultAcsClient acsClient=new DefaultAcsClient(defaultProfile);
        return acsClient;
    }
    /** 需要捕获AcsResponse响应的clientException异常
     * 2.获取视频上传地址(响应结果response)和凭证
     * 传入客户端权限ID、读取的文件
     */
    public static CreateUploadVideoResponse createUploadVideoResponse(DefaultAcsClient acsClient,String file) throws ClientException {
        //1.生成请求对象
        CreateUploadVideoRequest uploadVideoRequest=new CreateUploadVideoRequest();
        //2.存入请求体包含的文件
        uploadVideoRequest.setFileName(file);
        uploadVideoRequest.setTitle(file);
        LOG.info("传入的DefaultAcsClient：{}",acsClient);
        //3.VOD上传：上传视频封面，以下为ali提供默认封面图片
        uploadVideoRequest.setCoverURL("http://vod.aliyun.com/test_cover_url.jpg");
        //4.VOD上传：阿里云创建的分类ID:source （1000299007），carId为Long类型，加L类型转换
        uploadVideoRequest.setCateId(1000299007L);
        //5.VOD上传：阿里云创建的转码分类ID，设置转码加密类型的ID：HLS_transfer高清_mp4 --> f8c7f8b0023b86b2f2df16a6ca466b98
        uploadVideoRequest.setTemplateGroupId("f8c7f8b0023b86b2f2df16a6ca466b98");
        //6.配置请求超时
        uploadVideoRequest.setSysReadTimeout(1000);
        uploadVideoRequest.setSysConnectTimeout(1000);
        //7.返回响应结果
        return acsClient.getAcsResponse(uploadVideoRequest);
    }
    /**
     * 3.使用上传凭证和地址初始化OSS客户端，需要先base64解码
     * 传入上传权限和上传地址
     */
    public static OSSClient initialOSSClient(JSONObject uploadAccessKeyAuthority, JSONObject uploadAccessKeyEndpoint){
        //1.获取accessKey权限
        String accessKey=uploadAccessKeyAuthority.getString("AccessKeyId");
        String accessKeySecret=uploadAccessKeyAuthority.getString("AccessKeySecret");
        String securityToken=uploadAccessKeyAuthority.getString("SecurityToken");
        //2.获取bucket地址endpoint
        String endpoint=uploadAccessKeyEndpoint.getString("Endpoint");
        //注意OSSClient(传参顺序)
        return new OSSClient(endpoint,accessKey,accessKeySecret,securityToken);
    }
    /** 刷新响应数据（刷新请求）
     * 4.刷新上传凭证权限acsClient客户端
     */
    public static RefreshUploadVideoResponse refreshUploadVideoResponse(DefaultAcsClient acsClient) throws ClientException {
        //1.刷新请求
        RefreshUploadVideoRequest refreshUploadVideoRequest=new RefreshUploadVideoRequest();
        //2.请求格式
        refreshUploadVideoRequest.setAcceptFormat(FormatType.JSON);
        //3.请求的videoId
        refreshUploadVideoRequest.setVideoId("VideoID");
        //4.请求超时
        refreshUploadVideoRequest.setSysReadTimeout(1000);
        refreshUploadVideoRequest.setSysConnectTimeout(1000);
        //5.返回响应结果（传入请求）
        return acsClient.getAcsResponse(refreshUploadVideoRequest);
    }
    /** 获取响应中间层mezzanine对象
     * 5.根据videoId获取源文件信息:封面、描述、名字、大小等
     */
    public static GetMezzanineInfoResponse getMezzanineInfoResponse(DefaultAcsClient acsClient,String videoId) throws ClientException {
        GetMezzanineInfoRequest mezzanineInfoRequest=new GetMezzanineInfoRequest();
        mezzanineInfoRequest.setVideoId(videoId);
        //请求超时
        mezzanineInfoRequest.setAuthTimeout(3600L);
        LOG.info("mezzanine中间层请求数据：{}",mezzanineInfoRequest);
        return acsClient.getAcsResponse(mezzanineInfoRequest);
    }
    /**
     * 6.获取播放凭证函数:,实现授权播放
     */
    public static GetVideoPlayAuthResponse getVideoPlayAuthResponse(DefaultAcsClient acsClient,String videoId) throws ClientException{
        GetVideoPlayAuthRequest videoPlayAuthRequest=new GetVideoPlayAuthRequest();
        videoPlayAuthRequest.setVideoId(videoId);
        return acsClient.getAcsResponse(videoPlayAuthRequest);
    }
    /** 使用java重载特性：函数名相同，但函数的参数个数或类型不同
     * && 7.简单上传：单文件上传。视频点播不支持追加上传
     * 上传地址和流体文件inputStream
     */
    public static void uploadOSSLocalFile(OSSClient ossClient, JSONObject accessEndpoint, InputStream inputStream){
        String bucket=accessEndpoint.getString("Bucket");
        String fileName=accessEndpoint.getString("FileName");
        ossClient.putObject(bucket,fileName,inputStream);
    }
    public static void uploadOSSLocalFile(OSSClient ossClient, JSONObject accessEndpoint, String localFile){
        String bucket=accessEndpoint.getString("Bucket");
        String fileName=accessEndpoint.getString("FileName");
        File file=new File(localFile);
        LOG.info("uploadOSSLocalFile中的bucket：{} fileName：{} localFile： {}",bucket,fileName,file);
        //putObject：简单上传
        ossClient.putObject(bucket,fileName,file);
    }
    /**
     * && 8.方法main上传实例
     */
    /*public static void main(String[] args) throws ClientException {
        String ACCESS_KEY="LTAI5tKE5rrdxmV82fWcKPMe";
        String ACCESS_KEY_SECRET="3QFxcCVsam20vtYrhMCVgrvQq6trlI";
        String LOCAL_FILE="D:\\CEVENT_INFO\\cubic-3D-camera-web全栈片头_Trim.mp4";
        String FILE_KEY=UUID8Util.getShortUUID();
        try {
            //1.初始化acs客户端，获取authority权限
            DefaultAcsClient acsClient=initVODClient(ACCESS_KEY,ACCESS_KEY_SECRET);
            //2.文件名配置
            Date now=new Date();
            String date=new SimpleDateFormat("yyyy_MM_dd").format(now);
            String fileDate=new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(now);
            String path = new StringBuffer(fileDate).append("_")
                    .append(FILE_KEY).append(".mp4")
                    .toString();//.append(fileKey)
            //3.创建响应：客户端和文件
            CreateUploadVideoResponse uploadVideoResponse=createUploadVideoResponse(acsClient,path);
            //4.响应中获取参数
            String videoId=uploadVideoResponse.getVideoId();
            //5.需要将上传响应的结果，转换为JSONObject对象
            JSONObject accessAuthority=JSONObject.parseObject(
                    Base64.decodeBase64(uploadVideoResponse.getUploadAuth()),JSONObject.class);
            JSONObject accessEndPoint=JSONObject.parseObject(
                    Base64.decodeBase64(uploadVideoResponse.getUploadAddress()),JSONObject.class);
            LOG.info("这里的accessEndPoint：{}",accessEndPoint);
            //6.使用Auth和Address初始化OSS客户端
            OSSClient ossClient=initialOSSClient(accessAuthority,accessEndPoint);
            LOG.info("这里的OSSClient：{}",ossClient);
            //7.上传文件，同步上传会阻塞等待，耗时与文件大小和网络带宽有关
            uploadOSSLocalFile(ossClient,accessEndPoint,LOCAL_FILE);

            //8.获取响应中间层：视频信息
            GetMezzanineInfoResponse mezzanineInfoResponse=new GetMezzanineInfoResponse();
            mezzanineInfoResponse=getMezzanineInfoResponse(acsClient,videoId);
            //&& 阿里云jar里的实体类没有重写toString方法，每次打印日志都需要JSON.toString，所以实体类最好都加上toString
            LOG.info("VOD视频上传成功！获取视频信息mezzanine info response: {}", JSON.toJSONString(mezzanineInfoResponse));
        } catch (ClientException e) {
            LOG.info("上传视频失败 --！: {}",e.getLocalizedMessage());
            e.printStackTrace();
        }

    }*/
}
